bt.module({builder: function(bt) {
    var j$ = jQuery;
    var map;
    var mapThumbnail;
    var thumbnail;
    var ptScroller;
    var currentMarker;
    var path;
    var pathThumbnail;
    var markers;
    var infoWindows;
    var currentInfoWindowIndex = -1;
    var PHOTO_DISPLAY_COUNT = 4;
    var PHOTO_HEIGHT = 146;

    var _initMapEvent = function() {
        if(google) {
            var myOptions = {
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = bt.gmap.createMap("map", myOptions);
            mapThumbnail = bt.gmap.createMap("map-thumbnail", myOptions);
            thumbnail = bt.gmap.createPolygon({
                clickable: false,
                strokeColor: "#4D90FE",
                strokeWeight: 2,
                fillColor: "#4D90FE",
                fillOpacity: 0.1
            });

            bt.gmap.setOptions(map, {
                zoom: 8,
                minZoom: 4,
                streetViewControl: false,
                panControlOptions: {
                    position: google.maps.ControlPosition.RIGHT_TOP
                },
                zoomControlOptions: {
                    position: google.maps.ControlPosition.RIGHT_TOP
                }
            });
            bt.gmap.setOptions(mapThumbnail, {
                scrollwheel: false,
                disableDoubleClickZoom: true,
                maxZoom: 1, 
                disableDefaultUI: true
            });
            if (!j$(".photo-panel .selected .data .hidden-lat").val() ||
                !j$(".photo-panel .selected .data .hidden-lon").val()) {
                bt.gmap.zoomToChina(map);
            } else {
                var latlngbounds = new google.maps.LatLngBounds();
                map.fitBounds(latlngbounds);
            }
            bt.gmap.zoomToWorld(mapThumbnail);
            thumbnail.setMap(mapThumbnail);

            bt.gmap.addListener(map, "bounds_changed", function() {
                var bounds = bt.gmap.getBounds(map);
                var tr, bl, br, tl;
                if(bt.gmap.getZoom(map) > 6) {
                    var c = bounds.getCenter();
                    tr = bt.gmap.createLatLng(c.lat() + 3, c.lng() - 6);
                    bl = bt.gmap.createLatLng(c.lat() - 3, c.lng() + 6);
                    br = bt.gmap.createLatLng(c.lat() - 3, c.lng() - 6);
                    tl = bt.gmap.createLatLng(c.lat() + 3, c.lng() + 6);
                } else {
                    tr = bounds.getNorthEast();
                    bl = bounds.getSouthWest();
                    br = bt.gmap.createLatLng(bl.lat(), tr.lng());
                    tl = bt.gmap.createLatLng(tr.lat(), bl.lng());
                }
                thumbnail.setPath([tl, tr, br, bl]);
                bt.gmap.panToBounds(mapThumbnail, bounds);
            });

            bt.gmap.addListener(map, 'click', function(event) {
                _placeMarker(map, event.latLng.lat(), event.latLng.lng());
            });

            bt.gmap.addListener(mapThumbnail, "click", function(e) {
                bt.gmap.panTo(map, e.latLng.lat(), e.latLng.lng());
            });

            // render path
            var rtn = bt.tripUtils.renderPath(j$("#path-data"), {}, true);
            path = rtn.path;
            path.setMap(map);
            bt.gmap.panToBounds(map, rtn.bounds);
            markers = rtn.markers;
            infoWindows = rtn.infoWindows;

            j$.each(infoWindows, function(index, infoWindow) {
                j$("#info-window-" + index + " .right-here").live("click", function() {
                    var pos = markers[index].getPosition();
                    _placeMarker(map, pos.lat(), pos.lng());
                });
            });

            j$.each(markers, function(index, marker) {
                marker.setMap(map);
                marker.setZIndex(10);
                bt.gmap.addListener(marker, 'click', function() {
                    if(currentInfoWindowIndex >= 0) {
                        infoWindows[currentInfoWindowIndex].close();
                    }
                    infoWindows[index].open(map, markers[index]);
                    currentInfoWindowIndex = index;
                });
            });

            pathThumbnail = bt.gmap.createPolyline({
                map: mapThumbnail,
                path: path.getPath(),
                strokeColor: "#0695f8",
                strokeOpacity: 1.0,
                strokeWeight: 1
            });
        }
        // select & edit first photo
        ptScroller.scrollTo(j$(".photo-panel .selected").index(), function() {
            _editFloatForm(j$(".photo-panel .selected"));
        });

    };

    var _clearEditForm = function(target_form) {
        if(currentMarker) {
            currentMarker.setMap(null);
        }
        j$("#latitude", target_form).val("");
        j$("#longitude", target_form).val("");
        j$("#city", target_form).val("");
        j$("#province", target_form).val("");
        j$("#country", target_form).val("");
        j$("#text", target_form).text("");
        j$(".date", target_form).val("");
        j$(".hour", target_form).val("");
        j$(".minute", target_form).val("");
    };

    var _updateMarkerLocation = function() {
        var latLng = currentMarker.getPosition();
        $('#latitude').val(latLng.lat());
        $('#longitude').val(latLng.lng());
        if(google) {
            bt.gmap.convertCoordinateToGeo(latLng.lat(), latLng.lng(),
                function(country_code, country, province, city) {
                    var target = j$('#edit-waypoint-float-window .address');
                    var text = ""
                        + j$.map([city, province, country],
                                   function(x) {
                                       return x? x: null;
                                   }).join(", ");
                    target.show();
                    text = j$.trim(text)? text: "位置";
                    target.find(".text span").html(text);
                    target.find(".text .threedots_ellipsis").remove();
                    target.find(".text").removeAttr("threedots")
                        .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});
                    j$('#edit-waypoint-float-window .position').hide();
                    j$('#edit-waypoint-float-window .position input').val("");
                }
            );
            j$.ajax({
                url: "/query_timezone/",
                data: {lat: latLng.lat(),
                       lng: latLng.lng()},
                success: function(resp) {
                    j$("#time-select").val(resp.timezone);
                    j$("#time-select").change();
                }
            });
        }
    };

    var _placeMarker = function(map, lat, lng) {
        /*
         * Temp remove gmap dependency
         */
        if(google) {
            if (currentMarker) {
                currentMarker.setMap(null);
            }

            currentMarker = bt.gmap.createMarker({
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: bt.gmap.createLatLng(lat, lng),
                map: map,
                zIndex: google.maps.Marker.MAX_ZINDEX
            });

            _updateMarkerLocation();
            bt.gmap.addListener(currentMarker, 'dragend', _updateMarkerLocation);
        }
    };

    var _spliceDate = function (date) {
        j$("#timearea").find("input").removeClass("error");
        if ( j$("#year").val() !== "" ) {
            var _date = j$("#year").val() + "-" + j$("#month").val() + "-" + j$("#day").val() + " " + j$("#hour").val() + ":" + j$("#min").val() + ":" + j$("#sec").val();
            if ( moment(_date).isValid() ) {
                var _offset = moment(_date).tz(j$("#time-select").val()).format("ZZ");
                _date = moment(_date + " " + _offset, "YYYY-MM-DD HH:mm:ss ZZ").tz(j$("#time-select").val());
                var _alldate = _date.format("YYYY-MM-DD HH:mm") + " · " + j$("select#time-select option:selected").attr("data-offset");
                j$("#edit-waypoint-form").find("#date").val(j$("#year").val() + "-" + j$("#month").val() + "-" + j$("#day").val());
                j$("#edit-waypoint-form").find(".date").val(_date.format("YYYY-MM-DD HH:mm:ssZZ"));
                j$("#time-full span").removeClass("text-error").text(_alldate);
            }else{
                if ( j$("#month").val() > 12 || !j$.isNumeric( j$("#month").val()) ) { j$("#month").addClass("error"); }
                if ( j$("#day").val() > 31 || !j$.isNumeric( j$("#day").val()) ) { j$("#day").addClass("error"); }
                if ( j$("#hour").val() > 24 || !j$.isNumeric( j$("#hour").val()) ) { j$("#hour").addClass("error"); }
                if ( j$("#min").val() > 61 || !j$.isNumeric( j$("#min").val()) ) { j$("#min").addClass("error"); }
                j$("#time-full").find("span").text("时间错误，请重新选择").addClass("text-error");
            }
        }
    };

    var _changeTimezone = function (date) {
        var _old_tz = j$("#tz-name").val();
        j$("#time-select").off('change');
        j$("#time-select").on('change', function() {
            var _new_tz = j$(this).val();
            var _now = moment(date, "YYYY-MM-DD HH:mm:ss ZZ").tz(_new_tz);
            j$("#year").val( _now.format("YYYY") );
            j$("#month").val( _now.format("MM") );
            j$("#day").val( _now.format("DD") );
            j$("#hour").val( _now.format("HH") );
            j$("#min").val( _now.format("mm") );
            j$("#sec").val( _now.format("ss") );
            _spliceDate(date);
        });
    };

    var _editFloatForm = function(obj) {
        if(!obj) {
            obj = j$(".photo-panel .photo-item").first();
        }
        var _photo = obj.find('.photo');
        var _old_time = moment(_photo.attr("data-time"), "YYYY-MM-DD HH:mm:ss ZZ").tz(_photo.attr("data-tz-name"));
        j$(".photo-panel .selected").removeClass("selected");
        obj.addClass("selected");

        var target_form = j$("#edit-waypoint-form");
        if ( obj.hasClass("text-item") ) {
            j$("#update-waypoint-photo-form .change-photo span").text("添加照片");
        }else{
            j$("#update-waypoint-photo-form .change-photo span").text("更换照片");
        }
        j$("#update-waypoint-photo-form .save .save-hint").hide();
        _repositionFloatForm();

        _clearEditForm(target_form);

        j$("#text", target_form).val(obj.find(".hidden-text").text());
        j$("#year", target_form).val(_old_time.format("YYYY"));
        j$("#month", target_form).val(_old_time.format("MM"));
        j$("#day", target_form).val(_old_time.format("DD"));
        j$("#hour", target_form).val(_old_time.format("HH"));
        j$("#min", target_form).val(_old_time.format("mm"));
        j$("#sec", target_form).val(_old_time.format("ss"));
        j$("#tz-name", target_form).val(_photo.attr("data-tz-name"));
        j$("#tz-offset", target_form).val(_old_time.format("ZZ"));
        j$("#time-select", target_form).val(_photo.attr("data-tz-name"));

        _spliceDate( moment(_old_time).format("YYYY-MM-DD HH:mm:ss ZZ") );
        var _date = _photo.attr("data-time");
        _changeTimezone(_date);

        j$("#privacy", target_form).val(obj.find(".hidden-privacy").val());
        j$(".date", target_form).change();

        var lat = obj.find(".hidden-lat").val();
        var lng = obj.find(".hidden-lon").val();
        if(lat && lng) {
            lat = parseFloat(lat);
            lng = parseFloat(lng);
            _placeMarker(map, lat, lng);
            bt.gmap.setZoom(map, 8);
            bt.gmap.panTo(map, lat, lng);
        } else {
            j$('#edit-waypoint-float-window .address .text span').html("");
            j$('#edit-waypoint-float-window .address').hide();
            j$('#edit-waypoint-float-window .position').show();
        }

    };

    var _repositionFloatForm = function() {
        var obj = j$(".photo-panel .selected");
        var actual_num = obj.index() + 1;
        var offset = parseInt(j$(".photo-panel .photos").offset().top) - 93;
        var hide_photo_num = 0 - (offset - 35) / PHOTO_HEIGHT;
        var display_num = actual_num - hide_photo_num;
        if (display_num > PHOTO_DISPLAY_COUNT || display_num <= 0) {
            j$("#edit-waypoint-float-window").hide();
        } else {
            j$("#edit-waypoint-float-window").show().css("top", 120 + (display_num - 1) * PHOTO_HEIGHT);
        }
    };

    var _refreshMapPath = function(trip_id) {
        j$.ajax({
            type: "GET",
            url: "/trips/" + trip_id + "/path/",
            success: function(resp) {
                j$("#path-data").html(resp);
                var rtn = bt.tripUtils.renderPath(j$("#path-data ol"), {}, true);
                if(path) {
                    path.setMap(null);
                }
                if(pathThumbnail) {
                    pathThumbnail.setMap(null);
                }
                path = rtn.path;
                path.setMap(map);
                pathThumbnail = bt.gmap.createPolyline({
                    map: mapThumbnail,
                    path: path.getPath(),
                    strokeColor: "#0695f8",
                    strokeOpacity: 1.0,
                    strokeWeight: 1
                });

                j$.each(markers, function(index, marker) {
                    if(marker) {
                        marker.setMap(null);
                        marker = null;
                    }
                });

                j$.each(infoWindows, function(index, infoWindow) {
                    if(infoWindow) {
                        infoWindow.close();
                        infoWindow.setMap(null);
                        marker = null;
                    }
                });

                markers = rtn.markers;
                infoWindows = rtn.infoWindows;
                j$.each(infoWindows, function(index, infoWindow) {
                    j$("#info-window-" + index + " .right-here").live("click", function() {
                        var pos = markers[index].getPosition();
                        _placeMarker(map, pos.lat(), pos.lng());
                    });
                });

                j$.each(markers, function(index, marker) {
                    marker.setMap(map);
                    marker.setZIndex(10);
                    bt.gmap.addListener(marker, 'click', function() {
                        if(currentInfoWindowIndex >= 0) {
                            infoWindows[currentInfoWindowIndex].close();
                        }
                        infoWindows[index].open(map, markers[index]);
                        currentInfoWindowIndex = index;
                    });
                });
            }
        });
    };

    var _submitFloatForm = function() {
        if (j$.trim(j$("#edit-waypoint-form .date").val()) == "") {
            j$("#edit-waypoint-form .date").addClass("date-undefined");
            j$(".save-btn").css('opacity', 1);
            return;
        }

        var wp = j$(".photo-panel .selected");
        var trip_id = j$("#edit-waypoint-form").attr("data-trip-id");
        var wp_id = wp.attr("data-id");
        var args = j$("#edit-waypoint-form").serialize();

        if ( wp.data("create-text") === 1 ) {
            var url = "/trips/" + trip_id + "/add_waypoint/";
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: {csrfmiddlewaretoken: j$("#edit-waypoint-form input[name='csrfmiddlewaretoken']").val(),trip_id: trip_id, time: j$("#time-unix").val(),text: j$("#text").val()},
                success: function (data) {
                    if (data.error_code) {
                        alert(data.prompt);
                    }else{
                        j$("#update-waypoint-photo-form .save .save-hint").fadeIn();
                        j$('.selected .hidden-lat').val(j$('#latitude').val());
                        j$('.selected .hidden-lon').val(j$('#longitude').val());
                        j$('.selected .hidden-text').text(j$('#text').val());
                        wp.find('.photo').attr('data-time', j$("#edit-waypoint-form .date").val());
                        wp.find('.photo').attr('data-tz-name', j$('#time-select').val());
                        wp.attr("data-id", data.id);
                        wp.attr("data-new-create-text", 0);
                        wp.data("create-text", 0);
                        _refreshMapPath(trip_id);
                        _editNextItem();
                    }
                    j$(".save-btn").css('opacity', 1);
                }
            });
        }else{
            var url = "/trips/v1_1/" + trip_id + "/waypoints/" + wp_id + "/edit/";
            j$("#edit-waypoint-form").ajaxSubmit({
                type: "POST",
                url: url,
                data: args,
                dataType: 'json',
                success: function(resp) {
                    if(resp.error) {
                        alert(resp.error);
                    } else {
                        j$("#update-waypoint-photo-form .save .save-hint").fadeIn();
                        j$('.selected .hidden-lat').val(j$('#latitude').val());
                        j$('.selected .hidden-lon').val(j$('#longitude').val());
                        j$('.selected .hidden-text').text(j$('#text').val());
                        wp.find('.photo').attr('data-time', j$("#edit-waypoint-form .date").val());
                        wp.find('.photo').attr('data-tz-name', j$('#time-select').val());
                        _refreshMapPath(trip_id);
                        _editNextItem();
                    }
                    j$(".save-btn").css('opacity', 1);
                },
                error: function() {
                    j$(".save-btn").css('opacity', 1);
                }
            });
        }
    };

    var _doneWholePage = function() {
        var data = bt.misc.initPostData();
        data["editing"] = j$(".create-trip").hasClass("edit");
        var redirect = j$(".done-btn").attr("href");
        if (j$(".create-trip").attr("data-back-wp")) {
            redirect += "#wp" + j$(".create-trip").data("back-wp");
        }
        $.ajax({
            type: "POST",
            data: data,
            success: function(resp) {
                if(resp.error) {
                    alert(resp.error);
                } else {
                    if(resp.wp_ids.length > 0) {
                        _editFloatForm(j$("#wp" + resp.wp_ids[0]));
                        ptScroller.scrollTo(j$(".photo-panel .selected").index());
                        j$("#edit-waypoint-form .date").addClass("date-undefined");
                    } else {
                        j$(location).attr("href", redirect);
                    }
                }
            }
        });
    };

    var _editNextItem = function() {
        var next = j$(".photo-panel .selected").next();
        if(next.length > 0) {
            ptScroller.scrollNext(function() {
                _editFloatForm(next);
            });
        }
    };

    var _alertUnsavedChange = function() {
        var obj = j$(".photo-panel .selected");
        var target_form = j$("#edit-waypoint-form");
        var old_lat = parseFloat(obj.find(".hidden-lat").val());
        var old_lng = parseFloat(obj.find(".hidden-lon").val());
        var new_lat = parseFloat(j$('#latitude').val());
        var new_lng = parseFloat(j$('#longitude').val());
        if( (!old_lat && new_lat) ||
            (!old_lng && new_lng) ||
            Math.abs(old_lat - new_lat) > 1e-8 ||
            Math.abs(old_lng - new_lng) > 1e-8 ||
            obj.find(".hidden-text").text() != j$("#text", target_form).val() ||
            moment(obj.find(".photo").attr("data-time")).format() != moment(j$(".date", target_form).val()).format() ||
            obj.find(".photo").attr("data-tz-name") != j$("#time-select").val() ||
            obj.data("new-create-text") === 1 ) {
            return "您尚有未保存的改动，确定离开？";
        }
    };

    var _handleIECenterAlign = function() {
        if (j$.browser.msie && j$.browser.version <= 7) {
            var holder_w = j$(".photo-panel .info-mask").width();
            j$(".photo-panel .photo-item .info").each(function() {
                var text = j$(".info-text", j$(this));
                var w = (j$(".info-icon", j$(this)).width() + text.width() +
                         parseInt(text.css("margin-left")) +
                         parseInt(text.css("margin-right")));
                j$(".wrapper", j$(this)).css("padding-left", (holder_w - w) / 2);
            });
        }
    };

    var _addTextWaypoint = function () {
        var _currentWaypoint = j$(".photo-panel .selected");
        var _currentTime = _currentWaypoint.find(".photo").attr("data-time");
        var _textTime = moment(_currentTime).add('seconds', 10).format("YYYY-MM-DD HH:mm:ss ZZ");
        var _textTimezone = _currentWaypoint.find(".photo").attr("data-tz-name");
        var _textWaypoint = '<li class="photo-item text-item fl" id="" data-id="" data-create-text="1" data-new-create-text="1"><div class="photo" data-time="'+ _textTime +'" data-tz-name="'+ _textTimezone +'" data-photo="" data-photo-h="" data-photo-w=""><div class="text-item-icon"></div><img src="" alt="" style=""><div class="info-mask"></div><div class="info"><div class="display-table"><div class="wrapper display-cell"></div></div></div></div><div class="data hidden"><input type="hidden" class="hidden-lat" value=""><input type="hidden" class="hidden-lon" value=""><div class="hidden-text"></div><input type="hidden" class="hidden-privacy" name="privacy" value="0"></div><div class="photo-more-info hidden"><div class="photo-w640" data-photo="" data-photo-h="" data-photo-w=""><img src="" alt=""></div></div></li>';
        _currentWaypoint.after(_textWaypoint).next().click();
        j$("#time-unix").val(moment(_textTime).format("X"));
    };

    j$(document).ready(function() {
        // initDatepicker();
        initPhotosPanel();
        bt.gmap.initMapScript(_initMapEvent);
        ellipsisPOIInfo(j$(".photo-panel"));
        _handleIECenterAlign();

        j$(".photo-panel .photo-item .photo img").each(function() {
            bt.misc.centerAlignImg(j$(this), 132, 132, false);
        });
        j$(".photo-panel .photo-item .photo img").load(function() {
            bt.misc.centerAlignImg(j$(this), 132, 132, false);
        });

        var target_form = j$("#edit-waypoint-float-window");

        j$(".photo-panel").on("click", ".photo-item", function(e) {
            target_form.show();
            if(j$(this).hasClass("selected")) return;
            var msg = _alertUnsavedChange();
            if(msg) {
                var rtn = confirm(msg);
                if(rtn) {
                    _editFloatForm(j$(this));
                }
            } else {
                _editFloatForm(j$(this));
            }
            e.preventDefault();
            e.stopPropagation();
        });

        // safari 对个位数日期处理错误
        j$("#month, #day, #hour, #min").on('blur', function() {
            if ( j$(this).val().length === 1 ) {
                j$(this).val( "0" + j$(this).val() );
            }
            _spliceDate();
        });

        j$("#edit-waypoint-form .time-inner").hover(function() {
            j$(this).addClass("time-inner-show");
            j$("#timearea").show();
            $('#time-select').mouseleave(function(event) { event.stopPropagation(); });
        }, function () {
            j$(this).removeClass("time-inner-show");
            j$("#timearea").hide().find('input').blur();
            $('#time-select').mouseleave(function(event) { event.stopPropagation(); });
            _spliceDate();
        });

        var ajaxRequest = null;
        j$("#upload-popup .cancel").live("click", function() {
            if(ajaxRequest) {
                ajaxRequest.abort();
            }
            j$("#upload-popup").dialog("close");
        });
        j$("#new-photo", target_form).change(function() {
            var wp = j$(".photo-panel .selected");
            var trip_id = j$("#update-waypoint-photo-form").attr("data-trip-id");
            var wp_id = wp.attr("data-id");
            var args = j$("#update-waypoint-photo-form").serialize();
            var url = "/trips/" + trip_id + "/waypoints/" + wp_id + "/update_photo/";
            j$("#update-waypoint-photo-form").ajaxSubmit({
                type: "POST",
                url: url,
                data: args,
                dataType: 'json',
                beforeSend: function(jqXHR, settings) {
                    ajaxRequest = jqXHR;
                },
                beforeSubmit: function(arr, $form, options) {
                    if(j$.browser.msie) {
                        j$("#upload-popup .progress-percentage").html("");
                        j$("#upload-popup .progress-bar-inner").css(
                                "width", "100%");
                    } else {
                        j$("#upload-popup .progress-percentage").html("0%");
                        j$("#upload-popup .progress-bar-inner").css(
                                "width", 0);
                    }
                    j$("#upload-popup").dialog({
                        dialogClass: "upload-popup",
                        closeText: "",
                        modal: true,
                        height: 116,
                        resizable: false,
                        position: "center",
                        closeOnEscape: false,
                        width: 420
                    });
                },
                uploadProgress: function(e, position, total, percentComplete) {
                    j$("#upload-popup .progress-percentage").html(percentComplete + "%");
                    j$("#upload-popup .progress-bar-inner").css(
                            "width", percentComplete + "%");
                },
                success: function(resp) {
                    j$('.selected .photo img').attr('src', resp.photo_s);
                    j$(".selected .photo-more-info img").attr("src", resp.photo_w640);
                    j$(".selected .photo-more-info .photo-w640").attr("data-photo", resp.photo);
                    j$(".selected .photo-more-info .photo-w640").attr("data-photo-h", resp.photo_info.h);
                    j$(".selected .photo-more-info .photo-w640").attr("data-w", resp.photo_info.w);
                    ajaxRequest = null;
                    j$("#upload-popup").dialog("close"); 
                },
                error: function() {
                    ajaxRequest = null;
                    j$("#upload-popup").dialog("close"); 
                }
            });
        });

        j$(".save-btn", target_form).click(function() {
            var callback = function(country_code, country, province, city) {
                if (country_code) {
                    $('#country').val(country_code);
                } else {
                    $('#country').val("");
                }
                if (province) {
                    $('#province').val(province);
                } else {
                    $('#province').val("");
                }
                if (city) {
                    $('#city').val(city);
                } else {
                    $('#city').val("");
                }
                _submitFloatForm();
            }; // var callback

            var lat = $('#latitude').val();
            var lng = $('#longitude').val();
            j$(this).css('opacity', 0.3);
            if (lat && lng) {
                /* 
                 * Temp remove gmap dependency
                 *
                bt.gmap.convertCoordinateToGeo(lat, lng, callback);
                 */
                callback();
            } else {
                callback();
            }
        });
        j$(".done-btn").click(function() {
            var msg = _alertUnsavedChange();
            if(msg) {
                var rtn = confirm(msg);
                if(rtn) {
                    _doneWholePage();
                }
            } else {
                _doneWholePage();
            }
            return false;
        });
        j$(".close-btn").click(function() {
            target_form.hide();
        });

        j$(".text-btn").on("click", _addTextWaypoint);

        j$(".time .date", target_form).change(function(e) {
            if(j$.trim(j$(this).val()) == "") {
                j$(this).parent().addClass("error");
            } else {
                j$(this).parent().removeClass("error");
            }
        });

        j$(".timearea input", target_form).on('change', function() {
            _spliceDate();
        });

        j$(".address").click(function() {
            j$('#edit-waypoint-float-window .address').hide();
            j$('#edit-waypoint-float-window .position').show();
            j$('#edit-waypoint-float-window .position input').focus();
        });

        j$('#edit-waypoint-float-window .position input').blur(function() {
            if(j$('#edit-waypoint-float-window .address .text span').text()) {
                j$('#edit-waypoint-float-window .address').show();
                j$('#edit-waypoint-float-window .position').hide();
                j$('#edit-waypoint-float-window .position input').val("");
            }
        });

        j$('.pos-search input').keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                var address = j$(this).val();
                if(j$.trim(address)) {
                    bt.gmap.searchAddress(map, address);
                }
                e.preventDefault();
            }
        });

        j$(window).on('beforeunload', function() {
            return _alertUnsavedChange();
        });

        j$(document).keydown(function(e) {
            var key = (e.keyCode) || (e.which) || (e.charCode);//兼容IE(e.keyCode)和Firefox(e.which)
            var total_count = j$(".photo-panel .photo-item").length;
            var current_index = j$(".photo-panel .photo-item.selected").index();
            var _direction = '';
            if (!/input|textarea/.test(e.target.tagName.toLowerCase())) {
                if (key == "38" || key == "75") {//向上
                    _direction = current_index > 0 ? 'prev' : '';
                }
                if (key == "40" || key == "74") {//向下
                    _direction = current_index < total_count ? 'next' : '';
                }
            }
            if ( _direction === "" ) {
                return;
            }else if ( _direction == "prev" ) {
                j$(".photo-panel .selected").prev().trigger("click");
            }else if( _direction == "next" ) {
                j$(".photo-panel .selected").next().trigger("click");
            }
            var obj = j$(".photo-panel .selected");
            var actual_num = obj.index() + 1;
            var offset = parseInt(j$(".photo-panel .photos").offset().top) - 93;
            var hide_photo_num = 0 - (offset - 35) / PHOTO_HEIGHT;
            var display_num = actual_num - hide_photo_num;
            if (display_num > PHOTO_DISPLAY_COUNT) {
                ptScroller.scrollNext(function() {
                    _repositionFloatForm();
                });
            } else if( display_num <= 0) {
                ptScroller.scrollPrev(function() {
                    _repositionFloatForm();
                });
            }
        });

        j$('#photo-panel-close').on('click', function () {
            j$('#photo-panel-tip').hide();
        });
    });

    var ellipsisPOIInfo = function(obj) {
        var opts = {max_rows: 1, whole_word: false, allow_dangle: true};
        obj.find(".info-text").each(function() {
            if(!j$(this).attr("threedots")) {
                j$(this).ThreeDots(opts);
            }
        });
    };

    var initPhotosPanel = function () {
        var window_h = j$(window).height();
        var PHOTO_DISPLAY_COUNT_CUR = Math.floor((window_h - 150)/146);
        var panel_h = j$(".photo-panel .photo-panel-inner").height() - (PHOTO_DISPLAY_COUNT - PHOTO_DISPLAY_COUNT_CUR) * PHOTO_HEIGHT;
        var next_arrow_top = parseInt(j$(".navi .next").css("top")) - (PHOTO_DISPLAY_COUNT - PHOTO_DISPLAY_COUNT_CUR) * PHOTO_HEIGHT;
        var text_btn_top = parseInt(j$(".navi .text-btn-bg").css("top")) - (PHOTO_DISPLAY_COUNT - PHOTO_DISPLAY_COUNT_CUR) * PHOTO_HEIGHT;
        j$(".photo-panel .photo-panel-inner").height(panel_h);
        j$(".navi .next").css("top", next_arrow_top);
        j$(".navi .text-btn-bg").css("top", text_btn_top);
        j$(".navi .done-btn-bg").css("top", text_btn_top + 42);
        PHOTO_DISPLAY_COUNT = PHOTO_DISPLAY_COUNT_CUR;
        ptScroller = new ScrollPanel(".photo-panel", ".photos", {
            itemSize: 146,
            direction: ScrollPanel.VERTICAL,
            displayCount: PHOTO_DISPLAY_COUNT});
        ptScroller.navigator(j$(".navi"), function() {
            _repositionFloatForm();
        });
        ptScroller.addItem(j$(".photo-panel .photo-item").length);
    };

    var initDatepicker = function() {
        j$.datepicker.regional['zh-CN'] = {
            closeText: '关闭',
            prevText: '&#x3c;上月',
            nextText: '下月&#x3e;',
            currentText: '今天',
            monthNames: ['一月','二月','三月','四月','五月','六月',
                '七月','八月','九月','十月','十一月','十二月'],
            monthNamesShort: ['一','二','三','四','五','六',
                '七','八','九','十','十一','十二'],
            dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
            dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
            dayNamesMin: ['日','一','二','三','四','五','六'],
            weekHeader: '周',
            dateFormat: 'yy-mm-dd',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: true,
            yearSuffix: '年'};
        j$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
        j$("input.date").datepicker({
            yearRange: "-20:+0",
            changeYear: true
        });
    };

}});
